<template>
  <component :is="dialogList?.parentEleTag" v-bind="dialogList?.parentOptions">
    <el-form
      :model="form"
      label-width="auto"
      :rules="rules"
      label-position="left"
      ref="formRef"
    >
      <el-form-item
        v-for="item in detailsTitle"
        :label="item.title"
        :prop="item.name"
      >
        <!-- 输入框 -->
        <template v-if="item.type == 'text'">
          <el-input v-model="form[item.name]" :placeholder="item.placeholder" />
        </template>
        <!-- 密码框 -->
        <template v-if="item.type == 'password'">
          <el-input
            v-model="form[item.name]"
            :placeholder="item.placeholder"
            type="password"
            show-password
          />
        </template>
        <!-- 数字 -->
        <template v-if="item.type == 'number'">
          <el-input
            v-model="form[item.name]"
            type="number"
            :placeholder="item.placeholder"
          />
        </template>
        <!-- 日期 -->
        <template v-if="item.type == 'date'">
          <el-date-picker
            v-model="form[item.name]"
            :type="item.dataType"
            :placeholder="item.placeholder"
            style="width: 100%"
            :format="item.format"
            :value-format="item.format"
          />
        </template>
        <!-- 时间 -->
        <template v-if="item.type == 'time'">
          <el-date-picker
            v-model="form[item.name]"
            :type="item.dataType"
            :placeholder="item.placeholder"
            :format="item.format"
            :value-format="item.format"
          />
        </template>
        <!-- 时间段 -->
        <template v-if="item.type == 'quantum'">
          <el-date-picker
            v-model="form[item.name]"
            :type="item.dataType"
            range-separator="To"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :format="item.format"
            :value-format="item.format"
          />
        </template>
        <!-- 下拉框 -->
        <template v-if="item.type == 'select'">
          <el-select
            v-model="form[item.name]"
            :placeholder="item.placeholder"
            size="large"
            :filterable="true"
          >
            <el-option
              v-for="itemChild in item.options"
              :key="itemChild.value"
              :label="itemChild.label"
              :value="itemChild.value"
            />
          </el-select>
        </template>
        <!-- 复选框 -->
        <template v-if="item.type == 'checkbox'">
          <el-checkbox-group v-model="form[item.name]">
            <el-checkbox
              v-for="itemChild in item.options"
              :value="itemChild.value"
              :label="itemChild.label"
            >
            </el-checkbox>
          </el-checkbox-group>
        </template>
        <!-- 单选框 -->
        <template v-if="item.type == 'radio'">
          <el-radio-group v-model="form[item.name]">
            <el-radio
              v-for="itemChild in item.options"
              :value="itemChild.value"
              :label="itemChild.label"
            ></el-radio>
          </el-radio-group>
        </template>
        <!-- 上传图片 -->
        <template v-if="item.type == 'img'">
          <el-upload
            action="#"
            list-type="picture-card"
            class="imgUpload"
            :accept="item.file"
            v-model:file-list="item.fileList"
            :http-request="(params) => UploadFiles(params, item)"
          >
            <i class="iconfont icon-jietutupian"></i>
            <div class="desc">上传图片</div>
            <template #file="{ file }">
              <i
                class="iconfont icon-chahao"
                @click="deleteImg(file, item)"
              ></i>
              <el-image
                :src="file.url"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[baseUrl + file.pid]"
                fit="cover"
                class="imgOver"
              />
            </template>
          </el-upload>
        </template>
        <!-- 上传视频 -->
        <template v-if="item.type == 'video'">
          <el-upload
            :accept="item.file"
            class="videoUpload"
            id="video_kp"
            action=""
            list-type="picture-card"
            :name="item.name"
            v-model:file-list="item.fileList"
            :http-request="(params) => UploadFiles(params, item)"
          >
            <i class="iconfont icon-shipin"></i>
            <div class="desc">上传视频</div>
            <template #file="{ file }">
              <div>
                <i
                  class="iconfont icon-chahao"
                  @click="deleteImg(file, item)"
                ></i>
                <video
                  ref="videoRef"
                  :src="file.url"
                  :autoplay="false"
                  controls
                ></video>
              </div>
            </template>
          </el-upload>
        </template>
        <!-- 文本域 -->
        <template v-if="item.type == 'textArea'">
          <el-input
            v-model="form[item.name]"
            type="textarea"
            :placeholder="item.placeholder"
          />
        </template>
        <!-- 上传文件 -->
        <template v-if="item.type == 'file'">
          <el-upload
            :accept="item.file"
            v-model:file-list="item.fileList"
            class="fileUpload"
            action="#"
            :http-request="(params) => UploadFiles(params, item)"
          >
            <el-button type="primary">上传文件</el-button>
            <template #file="file">
              <div class="text">{{ file.file.name }}</div>
              <div class="operate">
                <i
                  class="iconfont icon-xiazai"
                  @click="downLoadFile(file.file)"
                ></i>
                <i
                  class="iconfont icon-shanchu"
                  @click="deleteImg(file.file, item)"
                ></i>
              </div>
            </template>
          </el-upload>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="save" @click="save(formRef)"
          >保存</el-button
        >
        <el-button type="primary" plain @click="handleClose">关闭</el-button>
      </el-form-item>
    </el-form>
  </component>
  <!-- </el-dialog> -->
</template>

<script setup lang="ts">
import {
  UploadProps,
  ElMessage,
  ElMessageBox,
  FormRules,
  ElLoading,
} from "element-plus";
import type { DialogProps } from "/@/types/listTypes.ts";
import {
  UploadFile,
  selectListByUuid,
  deleteFile,
  selectById,
  add,
  update,
  getInterSelected,
  delByUuids,
} from "../../api/editDialogApi";
const formRef = ref();
const form: any = reactive({});
const emits = defineEmits(["getData"]);
defineComponent({
  name: "eidtDialog",
});
const baseUrl = `${import.meta.env.VITE_APP_BASE_URL}/globalfile/download?pid=`;

// 删除加载的图片/
const deleteImg = (file: any, item: any) => {
  console.log(file, item);

  ElMessageBox.confirm(`确定要删除这个文件嘛?`).then(
    async () => {
      let res = (await deleteFile({ pid: file.pid })) as any;
      console.log(res);
      if (res.code == 200) {
        // 获得文件列表
        getFileList(item);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error(res.msg);
      }
    },
    () => {
      ElMessage.info("取消删除");
    }
  );
};

// 文件上传
async function UploadFiles(option: any, item: any) {
  console.log(item.fileList, option);

  var data = new FormData(); //自定义 参数类型必须为 FormData格式 此为强制要求
  data.append("file", option.file);
  data.append("uuid", item[item.name]);
  const res = (await UploadFile(data)) as any;
  if (res.code === 200) {
    console.log(res, res.data.filePid);

    //上传成功后保存uuid字段信息
    if (item[item.name] == "") {
      item[item.name] = res.data.uuid;
      form[item.name] = res.data.uuid;
    }

    item.fileList[item.fileList.length - 1] = {
      url: baseUrl + res.data.filePid,
      pid: res.data.filePid,
      name:(option.file.name.split('.'))[0]
    };
  } else {
    ElMessage.error(res.msg);
  }
}
// 获取文件列表
async function getFileList(item: any) {
  // 获得文件列表
  let result = (await selectListByUuid({ uuid: item[item.name] })) as any;

  if (result.code == 200) {
    console.log(result);
    // let arr = result.data.reverse();
    item.fileList = [];
    for (let i = 0; i < result.data.length; i++) {
      const element = result.data[i];
      item.fileList.push({ ...element, url: baseUrl + element.pid });
    }

    console.log(item.fileList);
  }
}

const dialogVisible = defineModel<boolean>("dialogVisible");
const dialogList = defineModel<DialogProps | any>("dialogList");

// 监听获得弹出框内容
let type = ref("add");
watch(dialogVisible, async (newValue, b) => {
  console.log(newValue, b);

  if (newValue) {
    getDialog();
    type.value = dialogList.value.modeType;
    // 获得下拉框数据
    let selectData = (await getInterSelected()) as any;
    detailsTitle.value.map((key: any) => {
      // key.value = selectData.data[key.name];
      if (
        key.type == "checkbox" ||
        key.type == "radio" ||
        key.type == "select"
      ) {
        key.options = selectData.data;
      }
    });

    if (type.value != "add") {
      let res = (await selectById({ pid: dialogList.value?.pid })) as any;
      if (res.code == 200) {
        detailsTitle.value.map((key: any) => {
          key[key.name] = res.data[key.name];
          form[key.name] = key[key.name];
          if (key.type == "file" || key.type == "img" || key.type == "video") {
            getFileList(key);
          }
        });
      } else {
        ElMessage.error(res.msg);
      }
    }
  }
});
const getDialog = () => {
  // 标签名
  dialogList.value.parentEleTag = "el-dialog";
  // 属性
  dialogList.value.parentOptions = {
    modelValue: dialogVisible,
    title: dialogList.value?.title,
    width: "37%",
    class: "dialogbox",
    "close-on-click-modal": false,
    appendToBody: true,
    "align-Center": true,
    center: true,
    "before-close": handleClose,
  };
  // 方法
  // dialogList.value.parentEvent = {};
};

const detailsTitle = ref<any>([
  {
    title: "项目名称：",
    name: "textform",
    type: "text",
    textform: "",
  },
  {
    title: "密码:",
    name: "passwordform",
    type: "password",
    passwordform: "",
  },
  {
    title: "数字：",
    name: "numberform",
    type: "number",
    numberform: 0,
  },
  {
    title: "规划项目图片：",
    name: "imageform",
    type: "img",
    imageform: "",
    fileList: [],
    file: "file",
  },
  {
    title: "规划项目视频：",
    name: "videoform",
    type: "video",
    videoform: "",
    fileList: [],
    file: "file",
  },
  {
    title: "规划编制相关规则方面说明：",
    name: "textareaform",
    type: "textArea",
    textareaform: "",
  },
  {
    title: "项目规划文件：",
    name: "fileform",
    type: "file",
    fileform: "",
    fileList: [],
    file: "file",
  },
  // {
  //   title: "复选框",
  //   name: "checkboxform",
  //   type: "checkbox",
  //   value: [],
  //   options: [],
  // },
  {
    title: "下拉框",
    name: "selectform",
    type: "select",
    selectform: "",
    options: [],
  },
  {
    title: "单选",
    name: "radioform",
    type: "radio",
    radioform: "",
    options: [],
  },
  {
    title: "日期",
    name: "dateform",
    type: "date",
    dateform: "",
    format: "YYYY-MM-DD",
    dataType: "date",
  },
  {
    title: "时间",
    name: "timeform",
    type: "time",
    timeform: "",
    dataType: "datetime",
    format: "YYYY-MM-DD HH:mm:ss",
  },
  // {
  //   title: "时间段",
  //   name: "timequantum",
  //   type: "quantum",
  //   value: "",
  //   dataType: "daterange",
  //   format: "YYYY-MM-DD",
  // },
]);

const rules = reactive<FormRules>({
  textform: [
    { required: true, message: "请输入项目名称", trigger: "blur" },
    {
      type: "string",
      message: "Please input correct email address",
      trigger: ["blur", "change"],
    },
  ],
});
// 保存
const save = async (formEl: any) => {
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      let loadingInstance1 = ElLoading.service({ fullscreen: true });
      // 编辑
      if (type.value == "edit") {
        form.pid = dialogList.value.pid;
        let res = (await update(form)) as any;
        if (res.code == 200) {
          ElMessage.success("编辑成功");
          dialogVisible.value = false;
          loadingInstance1.close();
          emits("getData");
        } else {
          ElMessage.error(res.msg);
          loadingInstance1.close();
        }
      } else if (type.value == "add") {
        form.drivermsgpid = 1;
        let res = (await add(form)) as any;
        if (res.code == 200) {
          ElMessage.success("保存成功");
          dialogVisible.value = false;
          loadingInstance1.close();
          emits("getData");
        } else {
          ElMessage.error(res.msg);
          loadingInstance1.close();
        }
      }
      // 清空表单
      clearForm();
    } else {
      // formRef.value.clearValidate();
      // dialogVisible.value = false;
      // setTimeout(() => {
      //   dialogVisible.value = true;
      // }, 0);
      ElMessage.error("请输入必填项");
    }
  });
};
// 关闭
const handleClose = () => {
  ElMessageBox.confirm("编辑的内容未保存，确定要关闭页面吗？").then(
    async () => {
      formRef.value.clearValidate();
      if (dialogList.value.modeType == "add") {
        let deleteStr = "";
        for (let i = 0; i < detailsTitle.value.length; i++) {
          const item = detailsTitle.value[i];
          if (
            (item.type == "img" ||
              item.type == "video" ||
              item.type == "file") &&
            item.value != ""
          ) {
            deleteStr += item.value + ",";
          }
        }
        if (deleteStr != "") {
          let res = (await delByUuids({ uuids: deleteStr })) as any;
          if (res.code == 200) {
            dialogVisible.value = false;
          }
        } else {
          dialogVisible.value = false;
        }
      }
      clearForm();

      dialogVisible.value = false;
    },
    () => {
      ElMessage.info("取消删除");
    }
  );
};

// 清空表单
const clearForm = () => {
  for (let i = 0; i < detailsTitle.value.length; i++) {
    const item = detailsTitle.value[i];

    item[item.name] = "";
    item.fileList = [];
  }

  for (const key in form) {
    form[key] = "";
  }
};
// 下载文件
const downLoadFile = (file: any) => {
  console.log(file);
  console.log(baseUrl + file.pid);

  let a = document.createElement("a") as any;
  a.style = "display: none"; // 创建一个隐藏的a标签
  a.download = file.name;
  a.href = baseUrl + file.pid;
  document.body.appendChild(a);
  a.click(); // 触发a标签的click事件
  document.body.removeChild(a);
};
</script>

<style scoped lang="scss">
@import "/@/styles/dialog/dialog.scss";
</style>
